package com.taobao.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.taobao.pojo.DBContext;

public abstract class CommonDBDao {
	private Connection conn = null;

	private Connection getConnection() {
		try {
			Class.forName("org.sqlite.JDBC");
			if(conn == null){
				conn = DriverManager.getConnection("jdbc:sqlite:" + "momo.db");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	private void closeConnection() {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void saveRequest(String sql, boolean close) throws Exception {
		Connection conn = getConnection();
		Statement stat = conn.createStatement();
		stat.executeUpdate(sql);
		if(close){
			closeConnection();
		}
	}

	public Object selectRequest(String sql, boolean close) throws Exception {
		Object rtn = null;
		Connection conn = getConnection();
		Statement stat = conn.createStatement();
		ResultSet rs = stat.executeQuery(sql);
		DBContext context = new DBContext();
		context.setResultSet(rs);
		rtn = process(context);
		if(close){
			closeConnection();
		}
		return rtn;
	}

	public abstract Object process(DBContext context) throws Exception;
}
